<template>
  <div class="map">
    <div class="header">
      <p @click="back"><van-icon name="arrow-left" /></p>
      <p>地图找房</p>
      <p></p>
    </div>
    <div class="main">
      <div id="container"></div>
    </div>
  </div>
</template>

<script type="text/javascript">
import { mapState } from "vuex";
export default {
  data() {
    return {
      citys: [],
    };
  },
  computed: {
    ...mapState(["areaList"]),
  },
  methods: {
    back() {
      history.back(-1);
    },
    getArea(id) {
      return this.$http.get(`/area/map?id=${id}`);
    },
    getData(map, data) {
      let { BMapGL } = window;
      console.log(data);
      if (data.status === 200) {
        // 遍历数据中的经纬度
        data.body.forEach((item) => {
          console.log(item);
          var point = new BMapGL.Point(
            item.coord.longitude,
            item.coord.latitude
          );
          var content = item.label;
          var label = new BMapGL.Label(content, {
            // 创建文本标注
            position: point, // 设置标注的地理位置
            offset: new BMapGL.Size(10, 20), // 设置标注的偏移量
          });
          label.setStyle({
            color: "white",
            width: "60px",
            height: "60px",
            lineHeight: "60px",
            textAlign: "center",
            borderRadius: "50px",
            borderColor: "#ccc",
            padding: "5px 8px",
            fontSize: "14px",
            fontFamily: "微软雅黑",
            background: "red",
          });
          map.addOverlay(label);

          var handleClick = (e) => {
            console.log(item);
            console.log(e.currentTarget.latLng.lng);
            map.centerAndZoom(e.target.content, 15);
            map.clearOverlays();
            this.getArea(item.value).then((res) => {
              console.log(res);
              this.getData(map, res.data);
            });
          };
          label.addEventListener("click", handleClick);
        });
      }
    },
  },
  mounted() {
    let { BMapGL } = window;
    console.log(this.citys);
    var map = new BMapGL.Map("container"); // 创建地图实例
    map.centerAndZoom(this.areaList.label, 12); // 初始化地图，设置中心点坐标和地图级别

    this.getArea(this.areaList.value).then((res) => {
      this.getData(map, res.data);
    });
  },
};
</script>

<style scoped >
#container {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0;
  font-family: "微软雅黑";
}
.map {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding:  10px;
}
.main {
  flex: 1;
  overflow: hidden;
}
</style>